package com.newhonor.server.config.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.newhonor.server.pojo.ResBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当未登录或者token失效时范围接口时，自定义返回结果
 *
 * @Author newhonor
 * @Date 2021/2/20 11:15
 * @Version 1.0
 **/
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        PrintWriter out = httpServletResponse.getWriter();
        ResBean resBean = ResBean.error("未登录，请登录!");
        resBean.setCode(401);
        out.write(new ObjectMapper().writeValueAsString(resBean));
        out.flush();
        out.close();
    }
}
